
// 导入 express
const express = require('express')
// 创建服务器的实例对象
const app = express()

const WebSocket = require('ws')
const bodyparser = require('body-parser');
const session = require('express-session');


// 存储聊天信息
let chatInfo = []
// 存储在线用户
let onlineUser = []

const wss = new WebSocket.Server({ port: 5001 })
// 建立websocket连接
wss.on('connection', (ws, req, res) => {
  console.log('server connection')
  // 获取当前连接websocket的用户uid
  let uid = req.url.substr(1)
  let index = onlineUser.findIndex(val => val.id === uid)
  if (index !== -1) {
    onlineUser[index].websocket = ws
  } else {
    onlineUser.push({
      websocket: ws,
      id: uid
    })

  }
  // 获取在线用户id数组
  let User = JSON.stringify({
    onlineUser: onlineUser.map(val => val.id),
    type: 'users'
  })
  // 通知所有在线用户有新用户上线
  onlineUser.forEach((client) => client.websocket.send(User))
  ws.on('message', (msg) => {
    // 将收到的消息转成对象格式
    const buf = Buffer.from(msg)
    let notice = buf.toString('utf-8')
    let Notice = JSON.parse(notice)

    // 通知当前用户消息发送成功
    ws.send(JSON.stringify({
      msg: Notice.msg,
      type: 'chat'
    }))
    // 存储当前用户发送的数据
    chatInfo.push({
      from: uid,
      to: Notice.receiver,
      msg: Notice.msg
    })
    console.log('app chatInfo:' + JSON.stringify(chatInfo))
    // 根据receiver匹配到接收消息的用户并发送通知
    onlineUser.forEach(function each (client) {
      if (client.id === Notice.receiver) {
        if (client.websocket.readyState === 1) {
          client.websocket.send(JSON.stringify({
            msg: Notice.msg,
            type: 'chat',
            from: uid,
            to: Notice.receiver,
          }));
        }
      }
    });
  })
  // 连接关闭后清除在线用户
  ws.on('close', res => {
    let newUserArr = []
    let newUserIds = []
    for (let i = 0; i < onlineUser.length; i++) {
      let val = onlineUser[i]
      if (val.id !== uid) {
        newUserArr.push(val)
        newUserIds.push(val.id)
      }
    }
    onlineUser = newUserArr
    let User = JSON.stringify({
      onlineUser: newUserIds,
      type: 'users'
    })
    onlineUser.forEach((client) => client.websocket.send(User))
  })

  ws.send(JSON.stringify({
    msg: '连接已建立',
    type: 'system'
  }))
})


//3.创建一个路由对象
let router = express.Router();

// 4.设置路由
router.get('/getchat', (req, res) => {
  let fromid = req.query.id
  let toid = req.query.friendId
  // 返回当前用户与消息接收用户的聊天记录
  let msgList = chatInfo.filter(val => (val.from === fromid && val.to === toid) || (val.from === toid && val.to === fromid))
  console.log('getchat msgList:fromid:' + fromid + '_toid:' + toid + '_' + JSON.stringify(msgList))
  res.send(msgList);
})

app.use(router);

app.use(bodyparser.urlencoded({
  extended: false
}))
// app.use(cors({
//     origin:'http://localhost:3000'
//   }))
app.use(session({
  secret: '随机字符串',
  resave: false,
  saveUninitialized: true
}));
app.use(express.static('./public'));

app.listen(5050, () => {
  console.log('running 5050')
})
